package com.atkxp.controller;

import com.atkxp.dao.ItemCFMapper;
import com.atkxp.pojo.*;
import com.atkxp.service.BlogService;
import com.atkxp.service.CommentService;
import com.atkxp.service.ItemCFService;
import com.atkxp.service.UserService;
import org.ocpsoft.prettytime.PrettyTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * @author user
 * @declaration
 * @create 2022/11/6-22:19
 */
@Controller
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    @Qualifier("blogServiceImpl")
    private BlogService blogService;

    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;

    @Autowired
    @Qualifier("commentServiceImpl")
    private CommentService commentService;

    @Autowired
    private ItemCFMapper itemCFMapper;

    @RequestMapping("/getAllBlog")
    public String showAllBlog(HttpServletRequest req){
        String basePath = req.getScheme() + "://" +
                req.getServerName() +
                ":" + req.getServerPort() +
                req.getContextPath() + "/";
        int pageNum;
        int pageSize;
        if(req.getParameter("pageNum") == null || Integer.parseInt(req.getParameter("pageNum")) <= 0){
            pageNum = 1;
        }else{
            pageNum = Integer.parseInt(req.getParameter("pageNum"));
        }
        if(req.getParameter("pageSize") == null){
            pageSize = Page.PAGE_SIZE;
        }else{
            pageSize = Integer.parseInt(req.getParameter("pageSize"));
        }
        Page<Blog> page = blogService.getBlogsLimit(pageNum, pageSize);
        page.setUrl(basePath + "/blog/getAllBlog");
        List<Blog> blogs = page.getItem();
        Map<Blog, MyPair<String, MyPair<User, Integer>>> map2 = new LinkedHashMap();
        for(Blog blog : blogs){
            map2.put(blog, new MyPair<String, MyPair<User, Integer>>(new PrettyTime().format(blog.getBlogDate()), new MyPair<User, Integer>(userService.showUserInfoByName(blog.getUserName()), commentService.getCommentNum(blog.getId()))));
        }
        req.getSession().setAttribute("blogs", map2);
        req.setAttribute("page", page);
        System.out.println(blogs.size());

        User user = (User) req.getSession().getAttribute("user");
        try {
            if(user != null) {
                List<Blog> blogs1 = ItemCFService.getRecommendBlogs(user.getId());
//                blogs1.forEach(System.out::println);
                Map<Blog, MyPair<String, MyPair<User, Integer>>> map3 = new LinkedHashMap();
                for(Blog blog : blogs1){
                    map3.put(blog, new MyPair<String, MyPair<User, Integer>>(new PrettyTime().format(blog.getBlogDate()), new MyPair<User, Integer>(userService.showUserInfoByName(blog.getUserName()), commentService.getCommentNum(blog.getId()))));
                }
                req.setAttribute("recommendBlogs", map3);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return "index";
    }

    @RequestMapping("/toAddBlog")
    public String toAddBlog(HttpServletRequest req, String name){
        req.setAttribute("name", name);
        User user = userService.showUserInfoByName(name);
        req.setAttribute("user", user);
        return "addBlog";
    }

    @ResponseBody
    @RequestMapping("/addBlog")
    public int addBlog(String content, String blogHead, String name, String firstTag, String secondTag, String thirdTag){
        User user = userService.showUserInfoByName(name);
        if(blogHead == null){
            blogHead = "默认标题";
        }
        List<User> users = userService.getAllUser();
        List<Blog> blogCount = blogService.getAllBlog();

        return blogService.addBlog(new Blog(0, user.getId(), user.getName(), blogHead, content, null, new Date(), 0, 0, firstTag, secondTag, thirdTag));
    }

    @RequestMapping("/showBlog")
    public String showBlog(int id, HttpServletRequest request, boolean isFa){
        Blog blog = blogService.getBlogById(id);
        User user = userService.showUserInfoByName(blog.getUserName());
        List<Blog> blogs = blogService.FindSimilarBlogByTag(blog);
        List<Comment> comments;
        if(isFa == true){
            comments = commentService.showAllCommentByBlogIdOrderByLike(blog.getId());
        }else{
            comments = commentService.showAllCommentByBlogId(blog.getId());
        }
        User login = (User) request.getSession().getAttribute("user");
        if(login != null){
            if(blogService.isExistHistoryBlog(login.getId(), id) == false){
                blogService.addHistoryBlog(login.getId(), id, new Date());
            }else{
                blogService.updateHistoryBlog(login.getId(), id, new Date());
            }
        }
        if(login != null){
            request.setAttribute("isCollected", blogService.isCollected(login.getId(), id));
        }
        if(login != null){
            request.setAttribute("isFollowed", userService.existFollowRelationship(login.getId(), user.getId()));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(blog.getBlogDate());
        request.setAttribute("blog", blog);
        request.setAttribute("user", user);
        request.setAttribute("time", time);
        Map<Comment, MyPair<String, Boolean>> comment = new LinkedHashMap<>();
        for(Comment comment1 : comments){
            comment.put(comment1, new MyPair<String, Boolean>(new PrettyTime().format(comment1.getCommentDate()).replace(" ", ""), userService.showUserInfoByName(comment1.getUserName()).getHeadImg() == null));
        }
        Map<Blog, MyPair<String, MyPair<User, Integer>>> map1 = new LinkedHashMap();
        for(Blog blog1 : blogs){
            map1.put(blog1, new MyPair<String, MyPair<User, Integer>>(new PrettyTime().format(blog1.getBlogDate()), new MyPair<User, Integer>(userService.showUserInfoByName(blog1.getUserName()), commentService.getCommentNum(blog1.getId()))));
        }
        request.setAttribute("recommendBlog", map1);
        request.setAttribute("comments", comment);
        return "showBlog";
    }

    @RequestMapping("/updateBlog")
    @ResponseBody
    public int updateBlog(String content, String blogHead, String name, int id, String firstTag, String secondTag, String thirdTag){
        Blog blog = blogService.getBlogById(id);
        User user = userService.showUserInfoByName(name);
        if(blogHead == null){
            blogHead = "默认标题";
        }
        return blogService.updateBlog(new Blog(id, user.getId(), user.getName(), blogHead, content, null, blog.getBlogDate(), blog.getLikes(), blog.getBrowsesNum(), firstTag, secondTag, thirdTag));
    }

    @RequestMapping("/deleteBlog")
    public String deleteBlog(int id, HttpServletRequest request, boolean flag){
        int userId = blogService.getBlogById(id).getUserId();
        String blogName = blogService.getBlogById(id).getBlogHead();
        List<Comment> comments = commentService.showAllCommentByBlogId(id);
        for (Comment comment : comments) {
            commentService.deleteCommentById(comment.getId());
        }
        itemCFMapper.deleteConnection(id);
        request.getSession().setAttribute("msg", "删除成功，删除的博客标题为" + blogName);
        blogService.deleteBlogById(id);
        System.out.println("删除成功");
        if(flag == true){
            return "redirect:/";
        }else{
            return "redirect:/blog/showMyBlog?userId="+userId;
        }
    }

    @RequestMapping("/showMyBlog")
    public String queryBlogByUserId(int userId, HttpServletRequest req){
        String basePath = req.getScheme() + "://" +
                req.getServerName() +
                ":" + req.getServerPort() +
                req.getContextPath() + "/";
        int pageNum;
        int pageSize;
        if(req.getParameter("pageNum") == null || Integer.parseInt(req.getParameter("pageNum")) <= 0){
            pageNum = 1;
        }else{
            pageNum = Integer.parseInt(req.getParameter("pageNum"));
        }
        if(req.getParameter("pageSize") == null){
            pageSize = Page.PAGE_SIZE;
        }else{
            pageSize = Integer.parseInt(req.getParameter("pageSize"));
        }
        User login = (User) req.getSession().getAttribute("user");
        if(login != null){
            Long blogCounts = blogService.getBlogCountLimitByUserId(login.getId());
            Long followCounts = userService.getFollowCount(login.getId());
            req.setAttribute("blogCounts", blogCounts);
            req.setAttribute("followCounts", followCounts);
        }
        Map map = new HashMap();
        map.put("userId", userId);
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        Page<Blog> page = blogService.getBlogByUserId(map);
        page.setUrl(basePath + "/blog/showMyBlog?userId=" + userId);
        List<Blog> blogs = page.getItem();
        Map<Blog, MyPair<String, User>> map2 = new LinkedHashMap<>();
        int browseCounts = 0;
        int likeCounts = 0;
        for(Blog blog : blogs){
            browseCounts += blog.getBrowsesNum();
            likeCounts += blog.getLikes();
            map2.put(blog, new MyPair<String, User>(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(blog.getBlogDate()), userService.showUserInfoByName(blog.getUserName())));
        }
        req.setAttribute("browseCounts", browseCounts);
        req.setAttribute("likeCounts", likeCounts);
        req.setAttribute("page", page);
        req.setAttribute("blogs", map2);
        return "showMyBlog";
    }

    @RequestMapping("/queryBlog")
    public String queryBlog(String blogName, HttpServletRequest req){
        String basePath = req.getScheme() + "://" +
                req.getServerName() +
                ":" + req.getServerPort() +
                req.getContextPath() + "/";
        int pageNum;
        int pageSize;
        if(req.getParameter("pageNum") == null || Integer.parseInt(req.getParameter("pageNum")) <= 0){
            pageNum = 1;
        }else{
            pageNum = Integer.parseInt(req.getParameter("pageNum"));
        }
        if(req.getParameter("pageSize") == null){
            pageSize = Page.PAGE_SIZE;
        }else{
            pageSize = Integer.parseInt(req.getParameter("pageSize"));
        }
        Map map = new HashMap();
        map.put("blogName", blogName);
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        Page<Blog> page = blogService.queryBlog(map);
        page.setUrl(basePath + "/blog/queryBlog?blogName=" + blogName);
        System.out.println(blogName);
        System.out.println(page.getUrl());
        List<Blog> blogs = page.getItem();
        Map<Blog, MyPair<String, MyPair<User, Integer>>> map2 = new LinkedHashMap();
        for(Blog blog : blogs){
            map2.put(blog, new MyPair<String, MyPair<User, Integer>>(new PrettyTime().format(blog.getBlogDate()), new MyPair<User, Integer>(userService.showUserInfoByName(blog.getUserName()), commentService.getCommentNum(blog.getId()))));
        }
        req.setAttribute("page", page);
        req.setAttribute("blogs", map2);
        req.setAttribute("blogName", blogName);
        return "queryBlog";
    }
    @ResponseBody
    @RequestMapping("/addLike")
    public int addLikes(int id, int userId){

        if(itemCFMapper.existConnection(userId, id) == null) {
            Map map = new HashMap();
            map.put("userId",userId);
            map.put("blogId",id);
            map.put("score", 2);
            itemCFMapper.addConnection(map);
        }
        else {
            Map map = new HashMap();
            map.put("userId",userId);
            map.put("blogId",id);
            int score = itemCFMapper.getScore(userId,id) + 2;
            if(score > 5) score = 5;
            map.put("score", score);
            itemCFMapper.updateConnection(map);
        }

        return blogService.addLikes(id);
    }

    @ResponseBody
    @RequestMapping("/deleteLike")
    public int deleteLikes(int id, int userId){

        if(itemCFMapper.existConnection(userId, id) == null) {
            Map map = new HashMap();
            map.put("userId",userId);
            map.put("blogId",id);
            map.put("score", 0);
            itemCFMapper.addConnection(map);
        }
        else {
            Map map = new HashMap();
            map.put("userId",userId);
            map.put("blogId",id);
            int score = itemCFMapper.getScore(userId,id) - 2;
            if(score < 0) score = 0;
            map.put("score", score);
            itemCFMapper.updateConnection(map);
        }

        return blogService.deleteLikes(id);
    }

    @ResponseBody
    @RequestMapping("/addBrowseNum")
    public int addBrowseNum(int id, int userId){

        if(itemCFMapper.existConnection(userId, id) == null) {
            Map map = new HashMap();
            map.put("userId",userId);
            map.put("blogId",id);
            map.put("score", 1);
            itemCFMapper.addConnection(map);
        }
        else {
            Map map = new HashMap();
            map.put("userId",userId);
            map.put("blogId",id);
            int score = itemCFMapper.getScore(userId,id) + 1;
            if(score > 5) score = 5;
            map.put("score", score);
            itemCFMapper.updateConnection(map);
        }

        return blogService.addBrowsesNum(id);
    }

    @RequestMapping("/toCollection")
    public String toCollection(HttpServletRequest req, int userId){
        String basePath = req.getScheme() + "://" +
                req.getServerName() +
                ":" + req.getServerPort() +
                req.getContextPath() + "/";
        int pageNum;
        int pageSize;
        if(req.getParameter("pageNum") == null || Integer.parseInt(req.getParameter("pageNum")) <= 0){
            pageNum = 1;
        }else{
            pageNum = Integer.parseInt(req.getParameter("pageNum"));
        }
        if(req.getParameter("pageSize") == null){
            pageSize = Page.PAGE_SIZE;
        }else{
            pageSize = Integer.parseInt(req.getParameter("pageSize"));
        }
        Map map = new HashMap();
        map.put("userId", userId);
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        Page<Blog> page = blogService.getCollectedBlogOrderByTime(map);
        page.setUrl(basePath + "/blog/toCollection?userId=" + userId);
        List<Blog> blogs = page.getItem();
        Map<Blog, MyPair<String, User>> map2 = new LinkedHashMap<>();
        for(Blog blog : blogs){
            map2.put(blog, new MyPair<String, User>(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(blog.getBlogDate()), userService.showUserInfoByName(blog.getUserName())));
        }
        req.setAttribute("page", page);
        req.setAttribute("blogs", map2);
        return "collection";
    }

    @RequestMapping("/toHistory")
    public String toHistory(HttpServletRequest req, int userId){
        String basePath = req.getScheme() + "://" +
                req.getServerName() +
                ":" + req.getServerPort() +
                req.getContextPath() + "/";
        int pageNum;
        int pageSize;
        if(req.getParameter("pageNum") == null || Integer.parseInt(req.getParameter("pageNum")) <= 0){
            pageNum = 1;
        }else{
            pageNum = Integer.parseInt(req.getParameter("pageNum"));
        }
        if(req.getParameter("pageSize") == null){
            pageSize = Page.PAGE_SIZE;
        }else{
            pageSize = Integer.parseInt(req.getParameter("pageSize"));
        }
        Map map = new HashMap();
        map.put("userId", userId);
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        Page<Blog> page = blogService.getHistoryBlogOrderByTime(map);
        page.setUrl(basePath + "/blog/toHistory?userId=" + userId);
        List<Blog> blogs = page.getItem();
        Map<Blog, MyPair<String, User>> map2 = new LinkedHashMap<>();
        for(Blog blog : blogs){
            map2.put(blog, new MyPair<String, User>(new PrettyTime().format(blogService.getHistoryBlogDate(userId, blog.getId())), userService.showUserInfoByName(blog.getUserName())));
        }
        req.setAttribute("page", page);
        req.setAttribute("blogs", map2);
        return "history";
    }

    @ResponseBody
    @RequestMapping("/collected")
    public int collect(int userId, int blogId){

        Map map = new HashMap();
        map.put("userId",userId);
        map.put("blogId",blogId);
        int score = 0;
        if(itemCFMapper.existConnection(userId, blogId) != null)
            score = itemCFMapper.getScore(userId,blogId) + 2;
        else score = 2;
        if(score > 5) score = 5;
        map.put("score", score);
        if(itemCFMapper.existConnection(userId, blogId) == null)
            itemCFMapper.addConnection(map);
        else
            itemCFMapper.updateConnection(map);
        return blogService.collectBlog(userId, blogId, new Date());
    }

    @ResponseBody
    @RequestMapping("/decollected")
    public int deCollect(int userId, int blogId){
        Map map = new HashMap();
        map.put("userId",userId);
        map.put("blogId",blogId);
        int score = 0;
        if(itemCFMapper.existConnection(userId, blogId) != null)
            score = itemCFMapper.getScore(userId,blogId) - 2;
        else score = 0;
        if(score < 0) score = 0;
        map.put("score", score);
        if(itemCFMapper.existConnection(userId, blogId) == null)
            itemCFMapper.addConnection(map);
        else
            itemCFMapper.updateConnection(map);
        return blogService.deleteCollectedBlog(userId, blogId);
    }

    @ResponseBody
    @RequestMapping("/dislike")
    public int disLike(int userId, int blogId) {
        Map map = new HashMap();
        map.put("userId",userId);
        map.put("blogId",blogId);
        map.put("score", 0);
        if(itemCFMapper.existConnection(userId, blogId) == null)
            return itemCFMapper.addConnection(map);
        else
            return itemCFMapper.updateConnection(map);
    }
}
